﻿namespace Resonator.Web.Controllers
{
	using System.Collections.Generic;
	using System.Globalization;
	using System.Web;
	using Core;
	using Resonator.Domain.Models;
	using Resonator.Domain.Services;

	public class ResolveController : ResonatorController
	{
		private readonly IResourceParserProvider _parserProvider;
		private readonly IResourceResolver _resolver;

		public ResolveController(IResourceParserProvider parserProvider, IResourceResolver resolver)
		{
			if( parserProvider == null ) throw new System.ArgumentNullException( "parserProvider" );
			if( resolver == null ) throw new System.ArgumentNullException( "resolver" );

			_parserProvider = parserProvider;
			_resolver = resolver;
		}

		public void Index()
		{
		}

		public void Resolve(HttpPostedFile resourceFile)
		{
			ResourceStream resourceStream = new ResourceStream( resourceFile.FileName, resourceFile.InputStream );

			IResourceParser parser = _parserProvider.Get( resourceStream );
			if( parser == null )
			{
				Flash["error"] = Strings.InvalidResourceFile;
				return;
			}

			IList<Resource> resources = parser.Parse( resourceStream );
			IList<ResolveResult> result = _resolver.Resolve( resources, new CultureInfo[] {CultureInfo.InvariantCulture} );

			PropertyBag["result"] = result;
			RenderView( "result" ); 
		}
	}
}
